import { NextRequest } from "next/server";
import { Prisma, PrismaClient } from '@prisma/client';
import { BaseController } from "@/utils/request/BaseController";
import prisma from '@/utils/db/PrismaService';
import { Auth, type ExtendedNextApiRequest, generateToken, hashPassword, ResponseHandler, verifyPassword, verifyToken, LogOperation } from "@/utils/decorator";
import { GloableResponseItem, ResponseEnum } from "@/utils/request/res";
import { getCurrentTimeInShanghai } from "@/utils";
import { GET as HttpGet, POST as HttpPost, PUT as HttpPut, DELETE as HttpDelete } from '@/utils/decorator';
import { createAllMethodHandlers } from '@/utils/request/routeRegistry';
class SystemUserController extends BaseController {

    @ResponseHandler()
    @HttpPost()
    static async systemLogin(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        const { user_name, password } = data;
        if (!user_name || !password) {
            return GloableResponseItem(ResponseEnum.fail, "用户名或密码不能为空", null);
        }
        const user = await prisma.sysUser.findUnique({
            where: { user_name },
        });
        if (!user) {
            return GloableResponseItem(ResponseEnum.fail, "用户不存在", null);
        }
        const isPasswordValid = await verifyPassword(password, user.password);
        if (!isPasswordValid) {
            return GloableResponseItem(ResponseEnum.fail, "密码错误", null);
        }
        const token = generateToken({ id: user.id, user_type: user.user_type ,dept_id: user.dept_id,nick_name: user.nick_name,user_name: user.user_name,role_type: user.role_type});
        return GloableResponseItem(ResponseEnum.success, "登录成功", { token: token });
    }

    // 获取用户信息
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getSystemUserInfo(request: ExtendedNextApiRequest) {
        // 通过token 获取用户id
        const token = request.headers.get('Authorization')?.split(' ')[1] || '';
        // console.log("token", token);
        const decoded = verifyToken(token);
        if (!decoded) {
            return GloableResponseItem(ResponseEnum.fail, "无效的token", null);
        }
        const userId = decoded.id;
        if (!userId) {
            return GloableResponseItem(ResponseEnum.fail, "无效的token", null);
        }
        // console.log("userId", userId);
        const user = await prisma.sysUser.findUnique({
            where: { id: Number(userId || 0), },
            select: {
                id: true,
                user_name: true,
                nick_name: true,
                dept_id: true,
                sex: true,
                status: true,
                user_type: true,
                role_type: true
            }
        });
        // console.log("user", user);
        if (!user) {
            return GloableResponseItem(ResponseEnum.unauthorized, "用户不存在", null);
        }
        // 判断用户是否停用
        if (user.user_type != '00') {
            if (user.status != '0') {
                return GloableResponseItem(ResponseEnum.unauthorized, "用户已停用", null);
            }
        }
        if (user.user_type != '00') {
            //查询用户机构信息
            const dept = await prisma.sysDept.findUnique({
                where: { id: user.dept_id ?? undefined },
            });
            // console.log("dept", dept);
            const parentDept = await prisma.sysDept.findUnique({
                where: { id: dept?.parent_id ?? undefined },
            });
            // console.log("parentDept", parentDept);

            // 获取用户机构id的所有父级机构id，一级一级的查找 最终拼接成 org001.org002.org003.org004的形式
            let deptHierarchyPath = '';
            let mqRoutingKey = '';
            let parentIds: string[] = [];
            
            if (dept) {
                // 递归查询所有父级机构
                let currentParentId = dept.parent_id;
                
                // 从当前机构的父级开始，一级一级往上查找
                while (currentParentId && currentParentId !== 0) {
                    const parentDept = await prisma.sysDept.findUnique({
                        where: { id: currentParentId },
                        select: {
                            id: true,
                            parent_id: true,
                            dept_name: true
                        }
                    });
                    
                    if (parentDept) {
                        // 将父级ID添加到数组开头，保持从根到叶的顺序
                        parentIds.unshift(parentDept.id.toString());
                        currentParentId = parentDept.parent_id;
                    } else {
                        break;
                    }
                }
                
                // 构建完整的层级路径：父级IDs + 当前机构ID
                const fullHierarchy = [...parentIds, dept.id.toString()];
                
                // 生成 org001.org002.org003.org004 格式的路径
                const orgPath = fullHierarchy.map(id => `${id}`);
                deptHierarchyPath = orgPath.join('.');
                
                // 生成 MQ 路由键：warning.org001.org002.org003.org004.#
                mqRoutingKey = `warning.${deptHierarchyPath}`;
            }
            
            const deptInfo = {
                dept_id: dept?.id,
                dept_name: dept?.dept_name,
                level: dept?.level,
                parent_dept_name: parentDept?.dept_name,
                hierarchy_path: deptHierarchyPath,  // 完整层级路径
                mq_routing_key: mqRoutingKey,       // MQ 路由键
                parent_ids: parentIds || []         // 所有父级机构ID数组
            }

            // 查询父级机构信息
            return GloableResponseItem(ResponseEnum.success, "获取用户信息成功", { ...user, deptInfo });
        } else {
            return GloableResponseItem(ResponseEnum.success, "获取用户信息成功", { ...user, deptInfo: {} });
        }
    }

    // 用户创建
    @Auth()
    @ResponseHandler()
    @LogOperation({
        module: "用户管理",
        operationName: "新增用户"
    })
    @HttpPost()
    static async addSystemUser(request: ExtendedNextApiRequest) {
        const data = request.customBody
        data.create_time = getCurrentTimeInShanghai()
        data.update_time = getCurrentTimeInShanghai()
        data.user_type = "01"
        data.password = await hashPassword(data.password)
        // 判断用户是否存在
        const user = await prisma.sysUser.findUnique({
            where: { user_name: data.user_name },
        });
        if (user) {
            return GloableResponseItem(ResponseEnum.fail, "用户已存在", null);
        }
        try {
            await prisma.sysUser.create({
                data
            })
        } catch (error) {
            console.log(error)
            return GloableResponseItem(ResponseEnum.fail, "新建失败", null);
        }
        return GloableResponseItem(ResponseEnum.success, "新建成功", null);
    }

    // 分页获取用户的列表
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getSystemUserList(request: ExtendedNextApiRequest) {
        const params: any = request.customBody
        const page = parseInt(params.page || '1');
        const pageSize = parseInt(params.pageSize || '10');
        const offset = (page - 1) * pageSize;
        const deptId = params.dept_id ? parseInt(params.dept_id) : null;

        const data = await prisma.$queryRaw<any[]>(Prisma.sql`
            SELECT u.*, d.dept_name 
            FROM sys_user u
            LEFT JOIN sys_dept d ON u.dept_id = d.id
            WHERE u.user_type = '01'
            ${deptId ? Prisma.sql`AND u.dept_id = ${deptId}` : Prisma.sql``}
            LIMIT ${pageSize} OFFSET ${offset}
        `);
        const total = await prisma.$queryRaw<{ count: BigInt }[]>(Prisma.sql`
            SELECT COUNT(*) as count
            FROM sys_user u
            LEFT JOIN sys_dept d ON u.dept_id = d.id
            ${deptId ? Prisma.sql`AND u.dept_id = ${deptId}` : Prisma.sql``}
            WHERE u.user_type = '01'
        `);
        const formatData = data.map(item => {
            return {
                ...item,
                key: item.user_id
            }
        })
        return GloableResponseItem(ResponseEnum.success, "", {
            data: formatData || [],
            total: total[0]?.count ? Number(total[0].count) : 0, // 将 BigInt 转换为 Number
            page,
            pageSize,
        });
    }

    // 更新用户
    @Auth()
    @ResponseHandler()
    @LogOperation({
        module: "用户管理",
        operationName: "更新用户信息"
    })
    @HttpPut()
    static async updateSystemUser(request: ExtendedNextApiRequest) {
        const data = await request.customBody;
        if (data.password) {
            data.password = await hashPassword(data.password)
        }
        data.update_time = getCurrentTimeInShanghai()
        await prisma.sysUser.update({
            where: { id: data.id },
            data
        })
        return GloableResponseItem(ResponseEnum.success, "更新成功", null);
    }

    // 删除用户
    @Auth()
    @ResponseHandler()
    @LogOperation({
        module: "用户管理",
        operationName: "删除用户"
    })
    @HttpDelete()
    static async deleteSystemUser(request: ExtendedNextApiRequest) {
        const data = await request.customBody;
        await prisma.sysUser.delete({ where: { id: data.id } });
        return GloableResponseItem(ResponseEnum.success, "删除成功", null);
    }

}
// 使用自动路由处理器创建所有HTTP方法处理函数
const handlers = createAllMethodHandlers(SystemUserController);

export const { GET, POST, PUT, DELETE } = handlers;